<?php

class Log {
	private static $messages = array();
	private static $on = false;
	private static $time;
	
	public static function turn_on() {
		self::$on = true;
		if (!isset(self::$time)) {
			self::$time = microtime(1);
		}
	}
	
	public static function turn_off() {
		self::$on = false;
	}
	
	public static function write() {
		if (!self::$on) {
			return;
		}
		$args = func_get_args();
		if ($args != array()) {
			$message = call_user_func_array('sprintf', $args);
		} else {
			$message = null;
		}
		
		$debug = debug_backtrace();
//		pr($debug);
		if (isset($debug[1])) {
			self::$messages[] = array_merge(array(
				'_time'     => microtime(1) - self::$time,
				'_message' => $message,
			), $debug[1]);
		} else {
			self::$messages[] = array_merge(array(
				'_time'     => microtime(1) - self::$time,
				'_message' => $message,
			), $debug[0], array(
				'function' => null,
				'class'    => null,
				'type'     => null,
			));
		}
	}
	
	public static function pr() {
//		pr(self::$messages);
		echo '<style>';
		echo ' .log-table { border-collapse: collapse; margin-top: 10px; font-size: 12px; font-family: Tahoma; }';
		echo ' .log-table th { padding: 3px 6px; background-color: #888; color: #fff; font-weight: bold; text-align: left; vertical-align: top; border-right: 1px solid #888; }';
		echo ' .log-table td { padding: 3px 6px; border: 1px solid #ddd; border-top: 0px; }';
		echo ' .log-table td i.a { color: #008; font-style: normal; }';
		echo ' .log-table td i.b { color: #080; font-style: normal; font-weight: bold; }';
		echo ' .log-table td.n { white-space: nowrap; }';
		echo '</style>';
		echo '<table class="log-table">';
		echo '<tr><th>time</th><th>method</th><th>message</th></tr>';
		foreach (self::$messages as $m) {
			if (isset($m['class']) && isset($m['type'])) {
				$method = '<i class="a">'.$m['class'].'</i><i class="b">'.$m['type'].'</i>'.$m['function'];
			} else {
				$method = $m['function'];
			}
			printf('<tr><td class="n">%0.5f</td><td class="n">%s</td><td>%s</td>', $m['_time'], $method, nl2br($m['_message']));
		}
		echo '</table>';
	}
}
